/*
 * @lc app=leetcode.cn id=979 lang=typescript
 *
 * [979] 在二叉树中分配硬币
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

function distributeCoins(root: TreeNode | null): number {
  // 后序遍历，保证先处理每个子节点
  const dfs = (root: TreeNode | null) => {
    if (root === null) return 0;
    let l = dfs(root.left);
    let r = dfs(root.right);
    // 负数表示从父节点取金币，正数表示移动金币给父节点，都算移动次数，所以要取绝对值
    ans += Math.abs(l) + Math.abs(r);
    // 返回当前节点上剩余几个金币
    return root.val + l + r - 1;
  };

  let ans = 0;

  dfs(root);

  return ans;
}
// @lc code=end
